package com.spring.core.mapping;

import com.spring.core.annotation.RequestMapping;
import com.spring.core.annotation.RestController;
import com.spring.core.context.AbstractApplicationContext;
import com.spring.core.context.AnnotationApplicationContext;
import com.spring.util.StringUtil;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 请求路径映射
 *
 * @author Zee
 * @version 1.0
 * @date 2021/10/13
 */
public class HandlerMapping {
    /**
     * 初始化handlerMapping
     *
     * @param context SpringContext
     */
    public void initHandlerMapping(AbstractApplicationContext context) {
        System.out.println("初始化Mapping:@RequestMapping...");
        for (Map.Entry<String, Object> entry : context.getIoc().entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if (!clazz.isAnnotationPresent(RestController.class)) {
                continue;
            }
            //类上面是否含有RequestMapping注解
            String basePath = "";
            if (clazz.isAnnotationPresent(RequestMapping.class)) {
                basePath = clazz.getAnnotation(RequestMapping.class).value();
            }
            //方法上面的requestMapping注解
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }
                RequestMapping methodMapping = method.getAnnotation(RequestMapping.class);
                String path = methodMapping.value();
                String url = StringUtil.urlHandler("/" + basePath + "/" + path);
                context.getMapping().put(url, method);
            }
        }
    }
}
